require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIRob = {}
HelperFunc.SetUIEnv(UIRob)
local this = UIRob
this.linkColor = "#" .. G.dataTable["t_global"][tostring(185)]["f_string_value"]
function UIRob.Init(data, closeFunc) 
    this.player_info = data
    local _name, _package = getUIName(PanelNames.UIRob)
    panelMgr:ShowUI(_name, _package, this.onCreate, Config.useLocalUI)
end

function UIRob.onCreate(obj) 
    if not this.hasInit then
        this.hasInit = true  
        this.btn_bg_close = obj:GetChild("Btn_BgClose") 
        this.btn_head = obj:GetChild("Btn_Head") 
        -- this.btn_help = obj:GetChild("Btn_Help")
        this.btn_rob = obj:GetChild("Btn_Rob")

        this.txt_close_tips = obj:GetChild("Text_CloseTips")
        this.txt_lv_num = obj:GetChild("Text_LvNum")
        this.txt_player_name = obj:GetChild("Text_PlayerName")
        this.txt_enemy_team = obj:GetChild("Text_EnemyTeam")
        this.txt_power_preview = obj:GetChild("Text_PowerPreview")

        this.red_name_controller = obj:GetController("RedName")
        
        this.list_hero = obj:GetChild("List_Hero")
        this.list_hero.itemRenderer = this.UpdateItemHeroRender

        -- this.rob_btn_title = this.btn_rob:GetChild("title")
        local cost_item = obj:GetChild("Com_Item")
        this.rob_loader_cost = cost_item:GetChild("Loader_icon")
        this.rob_txt_cost_num = cost_item:GetChild("Text_ResNum")
        this.rob_btn_add = cost_item:GetChild("Btn_Add")
        this.free_num_controller = obj:GetController("Free")
        -- this.txt_close_tips.text = "点击空白区域关闭"
        -- this.txt_enemy_team.text = "敌方阵容"
        -- this.rob_btn_title.text = "掠夺"
        this.txt_time_title = obj:GetChild("Text_TimeTitle")
        this.txt_time = obj:GetChild("Text_Time")
        this.txt_get_review = obj:GetChild("Text_GetReview")
        this.txt_freenum = obj:GetChild("Text_FreeNum")
        
        this.source = obj:GetChild("source")
        this.source_controller = obj:GetController("Show_source")
        this.source_controller:SetSelectedIndex(1)

        this.addEvent()
    end 
    this.initData()
end
 
function UIRob.initData() 
    this.UpdateFreeRobNum()
    plunderHandler.sendReqPlunderTargetInfo( this.player_info.playerId, this.player_info.targetId ) 
end

function UIRob.UpdateFreeRobNum()
    if this.txt_freenum then
        local cur_times = plunderHandler.today_free_rob_times or 0
        local free_num = dataTable.getDataTableByStringId("t_global", 339 ,"f_int_value")
        local remain_times = free_num - cur_times
        if remain_times < 0 then
            remain_times = 0
        end
        this.txt_freenum.text = string.format(getLanguage("RogueFree"), remain_times)
        if remain_times > 0 then
            this.free_num_controller:SetSelectedIndex(0)
        else
            this.free_num_controller:SetSelectedIndex(1)
        end
    end
end

-- partnerModelId @type number 英雄模型id 
-- partnerId @type number 英雄Id
-- level @type number 等级 
-- star @type number 星级
-- weaponLevel @type number 专武等级
function UIRob.ResUpdatePlayerInfo(msg)
    if msg and msg.info then 
        this.cur_player_data = {}
        this.cur_player_data.player_id = tostring(msg.info.playerId) 
        this.cur_player_data.skill_id = tostring(msg.info.skillId)
        this.cur_player_data.formation = {}
 
        this.btn_head:GetChild("head"):GetChild("HeadIcon").url =  logicMgr.SkinManager.GetHeroIconBySkinId(msg.info.pic)--EnumConst.AtlasPath.ICONAtlas .."icon_hero_".. (msg.info.pic or "")
        this.btn_head:GetChild("frame").url =  EnumConst.AtlasPath.ICONAtlas .. (msg.info.picFrame or "")

        local settle_time =  msg.info and msg.info.settleTime or 0
        if this.txt_time then  
            this.txt_time.text = getTimeStr(math.ceil(settle_time/1000))
        end 

        local cost_item_str = dataTable.getDataTableByStringId("t_global", 332 ,"f_string_value")
        local cost_item_tbl = decodeJsonStrToTabel(cost_item_str) 
        local cost_item_id = tonumber(cost_item_tbl[1][1])
        local cost_item_num = cost_item_tbl and cost_item_tbl[1] and tonumber(cost_item_tbl[1][2]) or 0
        local item_cfg = dataTable.getRow("t_item", cost_item_id)
        if item_cfg then 
            local item_cfg_icon = item_cfg.f_Icon 
            this.rob_loader_cost.url = "ui://ItemAtlas/"..item_cfg_icon --
        end

        if msg.info.itemAmount >= cost_item_num then
            this.is_engough_cost = true
        end
        this.cur_player_name = msg.info.name or ""
        this.txt_player_name.text = this.cur_player_name
        local power = msg.info.power and msg.info.power or 0
        this.txt_power_preview.text = HelperFunc.FormatResourceNum(power);
        this.txt_lv_num.text = string.format(getLanguage("RobLevel"), tostring(msg.info.lv))

        local total_plunder_val = msg.info and msg.info.totalPlunderVal or 0
        local red_val = msg.info and msg.info.redVal or 0

        local cur_red_name_cfg = dataTable.getDataTableByStringId("t_global", 365 ,"f_string_value")   
        if cur_red_name_cfg then
            local num = #cur_red_name_cfg
            local flag = true
            for i = num, 1, -1 do
                if red_val >= cur_red_name_cfg[i] then
                    this.red_name_controller:SetSelectedIndex(i)
                    flag = nil
                    break
                end
            end
            if flag then
                this.red_name_controller:SetSelectedIndex(0)
            end
        end


        if this.txt_get_review then
            -- local settle_time = this.player_info.settle_time or Config.serverTime
            -- local dis_time =  Config.serverTime - settle_time 

            local rob_param1 = dataTable.getDataTableByStringId("t_global", 361 ,"f_string_value")
            local rob_param1_1 = tonumber(rob_param1[1])/10000
            local rob_param1_2 = tonumber(rob_param1[2])/10000
            -- local rob_param1_tbl = decodeJsonStrToTabel(rob_param1)
            local rob_param2 = dataTable.getDataTableByStringId("t_global", 362 ,"f_int_value") 

            local param_a = dataTable.getDataTableByStringId("t_global", 334 ,"f_int_value")
            local param_b = dataTable.getDataTableByStringId("t_global", 335 ,"f_int_value")
            param_b = param_b/10000
            local total_power = msg.info.totalPower and tonumber(tostring(msg.info.totalPower)) or 0
            local my_total_power = tonumber( tostring(logicMgr.HeroManager.GetHerosSumPower()) )
            local value1 = param_a/10000
            local value2 = total_power/my_total_power 
            value2 = math.pow(value2, param_b) 
            if value2 < rob_param1_1 then
                value2 = rob_param1_1
            elseif value2 > rob_param1_2 then
                value2 = rob_param1_2
            end
            local value3 = value1 * value2 
            value3 = value3*100
            local value3_tmp = math.floor(value3)
            if value3 > value3_tmp then
                if value3 < 0.0001 then
                    value3 = "0.0001"
                elseif value3 < 0.001 then
                    value3 = string.format("%.4f", value3)
                    if value3 == "0.0000" then 
                        value3 = "0.0001"
                    end
                elseif value3 < 0.01 then
                    value3 = string.format("%.3f", value3)
                    if value3 == "0.00" then 
                        value3 = "0.01"
                    end
                elseif value3 < 0.1 then 
                    value3 = string.format("%.2f", value3)
                    if value3 == "0.00" then 
                        value3 = "0.01"
                    end
                else
                    value3 = string.format("%.1f", value3) 
                end
            else
                value3 = tostring(value3_tmp)
            end
             
            -- local value2_str
            -- local value2_tmp = tonumber(string.format("%.1f", value2*100))
            -- if value2_tmp == math.floor(value2_tmp) then
            --     value2_tmp = tostring(math.floor(value2_tmp))
            -- else
            --     value2_tmp = tostring(value2_tmp)
            -- end
            local review_content = value3.."%"
            if value2 > 1 then  
                -- value2_str = value2_tmp .."%"
                -- value2_str = string.TextColor(value2_str, "#BC2A36")

                review_content = string.TextColor(review_content, "#BC2A36")
            else
                -- value2_str = value2_tmp.."%"
                -- value2_str = string.TextColor(value2_str, "#117600")
                review_content = string.TextColor(review_content, "#117600")
            end
            
            -- local review_content = tostring(math.ceil(value1*100)).."% * "..value2_str
            -- review_content = string.format("%s%%(%s)", value3, review_content )
            this.txt_get_review.text = string.format(getLanguage("RogueTips07"), review_content)
        end

        local own_num = msg.info.itemAmount and tonumber(msg.info.itemAmount) or 0    
        if own_num >= cost_item_num then
            this.rob_txt_cost_num.text = tostring(own_num) .. "/" .. cost_item_num
        else 
            this.rob_txt_cost_num.text = table.concat({string.TextColor(getNumString(own_num),"#FF0000"), "/", tostring(cost_item_num)})
        end

        this.cur_player_data.formations = {}
        this.cur_player_data.formation_data = {}

        for k, v in pairs(msg.info.formations) do
            -- ["partnerId"] = 87961131548747,
            -- ["star"] = 20,
            -- ["partnerModelId"] = 16,
            -- ["fightVal"] = 1372,
            -- ["skinId"] = 0,
            -- ["activateBondIds"] = {
            -- },
            -- ["level"] = 3,
            -- ["sameNum"] = 0,
            if v and v.partnerModelId ~= 0 then
                local item = {}
                local cfg = dataTable.getDataTableByStringId("t_hero", v.partnerModelId)
                item.partnerId = tostring(v.partnerId) 
                item.partnerModelId = v.partnerModelId
                item.name = getLanguage(cfg.f_HeroName)
                item.level = v.level or 0
                item.star = v.star or 0 
                item.icon = cfg.f_HeroIcon
                item.skinId = v.skinId
                item.activate_bond_ids = v.activateBondIds
                item.sameNum = v.sameNum
                item.fightVal = v.fightVal 
                item.type = cfg.f_HeroType 
                table.insert(this.cur_player_data.formation_data, item)
                local formation_item = {}
                formation_item["partnerId"] = tostring(v.partnerId)
                formation_item["partnerModelId"] = v.partnerModelId
                formation_item["level"] = v.level
                formation_item["star"] = v.star
                formation_item["weaponLevel"] = 0
                formation_item["icon"] = "" 
                formation_item["state"] = 0 
                formation_item["power"] = v.fightVal
                this.cur_player_data.formation[k] = formation_item 
            end
        end
        for i = 1, 6 do
            if this.cur_player_data.formation[i] == nil then
                local formation_item = {}
                formation_item["partnerId"] = 0
                formation_item["partnerModelId"] = 0
                formation_item["level"] =0
                formation_item["star"] = 0
                formation_item["weaponLevel"] = 0
                formation_item["icon"] = "" 
                formation_item["state"] = 0 
                formation_item["power"] = 0
                this.cur_player_data.formation[i] = formation_item
            end
        end 
        this.list_hero.numItems = #this.cur_player_data.formation_data
    end
end

--
function UIRob.UpdateItemHeroRender( index, obj) 
    local quality = obj:GetChild("quality")
    local qualityBG = obj:GetChild("qualityBG")
    local icon = obj:GetChild("icon") 
    local lv = obj:GetChild("level")
    local lvbg = obj:GetChild("n29")
    local typeIcon = obj:GetChild("Occupation")
    local typeShowController = obj:GetController("Occupation")
    local hasUse = obj:GetController("ctrlHadUsed")
    local hadBattle = obj:GetController("ctrlHadBattle")
    local hadAssist = obj:GetController("ctrlHadAssist")
    local choose = obj:GetChild("maskChoose")
    local unActive = obj:GetChild("unActive")
    local emptyCtrl = obj:GetController("empty")
    local banCtrl = obj:GetController("Ban")
    local circletype = obj:GetController("CircleType")
    local circleCtrl = obj:GetController("Circle")
    local comIcon = obj:GetChild("Com_icon")  
    local enemySelectCtrl = obj:GetController("HadSelect")
    local levelShowCtrl = obj:GetController("isShowLevel")--0显示等级以及底框 1不显示
    if quality then
        quality.visible = false
        qualityBG.visible = false
    end
    icon.visible = false
    obj.touchable = false

    local item_info = this.cur_player_data and this.cur_player_data.formation_data and this.cur_player_data.formation_data[index + 1]
    if item_info then 
        if emptyCtrl then
            emptyCtrl.selectedIndex = 0
        end
        if item_info.star ~= nil then
            item_info.quality = logicMgr.HeroManager.starToQuality(item_info.star);
        end 
        -- local isban, isSeason = logicMgr.RankBattleManager.IsBan(item_info.partnerModelId, nil)
        -- if banCtrl then
        --     if isban then
        --         if isSeason then
        --             banCtrl.selectedIndex = 1
        --         else
        --             banCtrl.selectedIndex = 2 
        --         end
        --     else
                banCtrl.selectedIndex = 0
        --     end
        -- end 
        if circleCtrl and circleCtrl.selectedIndex == 1 then
            if circletype then
                if isSeason then
                    circletype.selectedIndex = 1
                else
                    circletype.selectedIndex = 2
                end
            end
        end  
        if logicMgr.RankBattleManager.BanPick() and enemySelectCtrl then
            if logicMgr.RankBattleManager.BPCanChooseHeroByModelId(item_info.partnerModelId) then
                enemySelectCtrl.selectedIndex = 1
            else
                enemySelectCtrl.selectedIndex = 0
            end
        end 
        local barController = obj:GetController("Bar")
        if barController ~= nil then
            barController.selectedIndex = 0
        end
        local newController = obj:GetController("new")
        if newController ~= nil then 
            newController.selectedIndex = 0
        end
        local showSSRController = obj:GetController("SSR")
        if showSSRController ~= nil then 
            showSSRController.selectedIndex = 0
        end
        hasUse:SetSelectedIndex(0)
        hadBattle:SetSelectedIndex(0)
        hadAssist:SetSelectedIndex(0)
        choose.visible = false
        unActive.visible = false
 
        if levelShowCtrl ~= nil then
            if item_info.level ~= nil and item_info.level > 0 then 
                levelShowCtrl.selectedIndex = 0 
                lv.visible = true
                lvbg.visible = true
                local level, lvType = logicMgr.HeroManager.getHeroShowLevelByPartnerId(item_info.partnerId)
                lv.text = string.TextColor(string.format(getLanguage("Level"), level), logicMgr.HeroManager.lvColors[lvType])
            else 
                levelShowCtrl.selectedIndex = 1 
            end
        end
 
        if item_info.star ~= nil and item_info.star > 0 then 
            local numstar = math.floor(item_info.star * 0.0001);
            if numstar > 5 then
                numstar = 5
            end 
        end
        if item_info.icon ~= nil then
            if circleCtrl and circleCtrl.selectedIndex == 1 then
                comIcon.visible = true
                comIcon:GetChild("icon").url = EnumConst.AtlasPath.ICONAtlas .. item_info.icon
            else
                icon.visible = true
                icon:GetChild("icon").url = EnumConst.AtlasPath.ICONAtlas .. item_info.icon
            end
            icon.visible = true
            icon:GetChild("icon").url = EnumConst.AtlasPath.ICONAtlas .. item_info.icon 
            if item_info.quality == nil or item_info.quality == 0 then
                item_info.quality = 1
            elseif item_info.quality > #Config.IconQuality then
                item_info.quality = #Config.IconQuality
            end
            quality.visible = true
            qualityBG.visible = true
            quality.url = EnumConst.AtlasPath.ICONAtlas .. Config.IconFrame[item_info.quality]
            qualityBG.url = EnumConst.AtlasPath.ICONAtlas .. Config.IconQuality[item_info.quality] 
        end
        if typeShowController ~= nil then
            if item_info.type ~= nil and EnumConst.HeroTypeIcon[item_info.type] ~= nil then
                typeShowController.selectedIndex = 0
                typeIcon.url = EnumConst.AtlasPath.ICONAtlas .. EnumConst.HeroTypeIcon[item_info.type]
            else
                typeShowController.selectedIndex = 1
            end
        end
        
        if item_info.state ~= nil then 
            if ZZMathBit.andOp(item_info.state, EnumConst.HeroHeadStateEnum.UnActive) > 0 then
                unActive.visible = true
            else
                unActive.visible = false
            end
            if ZZMathBit.andOp(item_info.state, EnumConst.HeroHeadStateEnum.DEAD) > 0 then
                obj.grayed = true
            else
                obj.grayed = false
            end
        else
            hadBattle:SetSelectedIndex(0)
        end
         
        if item_info.new ~= nil and newController ~= nil then
            newController.selectedIndex = 1
        end
        if item_info.showSSR and showSSRController ~= nil then
            showSSRController.selectedIndex = 1
        end 
    end

end


function UIRob.addEvent() 
    this.btn_bg_close.onClick:Add(this.CloseSelf)   
    -- this.btn_help.onClick:Add(this.onClickHelp) 
    this.btn_rob.onClick:Add(this.onClickRob) 
    this.rob_btn_add.onClick:Add(this.onClickAddPlunder) 
    this.rob_loader_cost.onClick:Add(this.onClickSource)
    this.rob_txt_cost_num.onClick:Add(this.onClickSource)
    -- this.source.onClick:Add(this.onClickCloseSource)
end

function UIRob.removeEvent() 
    this.btn_bg_close.onClick:Clear()  
    this.btn_head.onClick:Clear()  
    -- this.btn_help.onClick:Clear()  
    this.btn_rob.onClick:Clear()
    this.rob_btn_add.onClick:Clear()
    this.rob_loader_cost.onClick:Clear()
    this.rob_txt_cost_num.onClick:Clear()
    -- this.source.onClick:Clear()
end

-- function UIRob.onClickCloseSource()
--     this.source_controller:SetSelectedIndex(1)
-- end

function UIRob.onClickSource() 
    if this.source_controller.selectedIndex == 1 then
        this.source_controller:SetSelectedIndex(0)
        logicMgr.ItemManager.updateSourceUI(this.source, {200005}, function ()
            this.source_controller:SetSelectedIndex(1) 
        end, function () 
            this.source_controller:SetSelectedIndex(1)
            this.CloseSelf()
        end );
    else
        this.source_controller:SetSelectedIndex(1)
    end
    -- this.source = obj:GetChild("source") 
        
end

function UIRob.CloseSelf() 
    closeUI(PanelNames.UIRob)
end
 
-- function UIRob.onClickHelp()  
--     local txts = {};
--     txts["title"] = "RogueHelpTitle01"
--     txts["des"] = "RogueHelpDes01"
--     -- txts["tipsTitle"] = "RogueHelpTitle01"
--     showUI(PanelNames.CommonTips, txts);
-- end

function UIRob.onClickAddPlunder()

    local up_count = dataTable.getDataTableByStringId("t_global", 324 ,"f_int_value") 
    if plunderHandler.cur_buy_plunder_count >= up_count then
        UISysTips.AddMsg(getLanguage("ErrorCode_172078"))
        return
    end
    showUI(PanelNames.UIRobTicketPurchase)
    -- local need_num = dataTable.getDataTableByStringId("t_global", 323 ,"f_int_value") 
    -- local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
    -- pop.Init("48", function(b)
    --     if b then 
    --         local own_num = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) or 0
    --         if own_num >= need_num then
    --             plunderHandler.sendReqBuyPlunderItem()
    --         else
    --             UISysTips.AddMsg(getLanguage("Character_Tips7"))
    --         end 
    --     end
    -- end, tostring(need_num), "1")
end

function UIRob.ResAddPlunderItem( msg )  
    if this.rob_txt_cost_num then 
        local cost_item_str = dataTable.getDataTableByStringId("t_global", 332 ,"f_string_value")
        local cost_item_tbl = decodeJsonStrToTabel(cost_item_str)  
        local cost_item_num = cost_item_tbl and cost_item_tbl[1] and tonumber(cost_item_tbl[1][2]) or 0 
        local own_num = logicMgr.ItemManager.getItemCountbyItemTypeAndItemModelId(EnumConst.ItemTableEnum.Item, 200005) or 0  
        if own_num >= cost_item_num then
            this.is_engough_cost = true
        end 
        -- this.rob_txt_cost_num.text = tostring(own_num)
 
        if own_num >= cost_item_num then
            this.rob_txt_cost_num.text = tostring(own_num) .. "/" .. cost_item_num
        else 
            this.rob_txt_cost_num.text = table.concat({string.TextColor(getNumString(own_num),"#FF0000"), "/", tostring(cost_item_num)})
        end

    end
end
  
function UIRob.onClickRob()  
    plunderHandler.Track_clickPlunder(this.cur_player_data.player_id)

    if plunderHandler.change_plunder_function_type == 0 then
        UISysTips.AddMsg(getLanguage("ErrorCode_172084"))
        AudioManager.Play(2010)
        return
    end

    local cur_total_time = plunderHandler.rob_total_time 
    local up_time = dataTable.getDataTableByStringId("t_global", 321 ,"f_int_value") 
    local cur_progress = cur_total_time/up_time
    if cur_progress >= 1 then
        UISysTips.AddMsg(getLanguage("ErrorCode_172074"))
        AudioManager.Play(2010)
        return
    end

    local cur_times = plunderHandler.today_free_rob_times or 0
    local free_num = dataTable.getDataTableByStringId("t_global", 339 ,"f_int_value")
    local remain_times = free_num - cur_times
    if remain_times < 0 then
        remain_times = 0
    end
    if remain_times <= 0 then
        if not this.is_engough_cost then
            UISysTips.AddMsg(getLanguage("RogueTips01"))
            AudioManager.Play(2010) 
            return
        end
    end
    AudioManager.Play(1054)
    -- local data = {}
    -- data.player_id = this.cur_player_data.player_id
    -- data.formation = this.cur_player_data.formation
    -- data.type = 1
    -- data.historyId = 0
    -- plunderHandler.sendReqPlunderBattle( data ) --对战
    -- this.CloseSelf() 
    if not isOpenUI(PanelNames.UIBattleTeam) then
        AudioManager.Play(1054)

        plunderHandler.atk_target_name = this.cur_player_name
        local param = {}
        param.playerId = 0
        param.power = 0
        param.type = EnumConst.FormationType.Plunder
        param.formation = plunderHandler.atk_formation or {} 
        param.oppo_formation = this.cur_player_data.formation or {} 
        param.supSkillId = this.cur_player_data.skill_id
        showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.Plunder, param, function(formations)
            local flag = true;
            if formations[1] ~= nil then
                for i = 1, #formations[1] do
                    if formations[1][i] ~= nil and tonumber(tostring(formations[1][i])) > 0 then
                        flag = false;
                        break ;
                    end
                end
            end
            if flag then
                UISysTips.AddMsg("需要上阵至少一名英雄");
            else 
                plunderHandler.atk_formation = formations[1]
                local data = {}
                data.playerId = this.cur_player_data.player_id
                data.formation = formations[1]
                data.type = 1
                data.historyId = 0
                data.targetId = this.player_info.targetId or 0
                plunderHandler.rob_item_data = this.cur_player_data.player_id
                plunderHandler.is_rob = true
                plunderHandler.sendReqPlunderBattle( data ) --对战

            end 
        end, function() 
        end)
        this.CloseSelf()
    end

end
 
function UIRob.OnDestroy() 
    this.removeEvent()
    this.hasInit = nil
    this.is_engough_cost = nil
end

return UIRob
